package com.zsl.swing.redis.desktop.utils;

import com.alibaba.fastjson.JSON;
import com.zsl.swing.redis.desktop.model.OftenUseKeyModel;

import java.io.File;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class OftenUseKeyUtils {

    private static final String PARENT_DIR = ConfigUtils.BASE_PATH + "often-use" + File.separator;

    static {
        File f = new File(PARENT_DIR);

        if(!f.exists()){
            f.mkdirs();
        }
    }


    public static List<OftenUseKeyModel> getOftenUseKeyList(String uniqueId, int dbIndex){

        String keyFileName = buildFileName(uniqueId, dbIndex);

        File f = new File(keyFileName);

        String result = ConfigUtils.readFile2String(f);

        List<OftenUseKeyModel> targetList = StringUtils.isEmpty(result) ? Collections.emptyList() : JSON.parseArray(result, OftenUseKeyModel.class);

        Comparator<OftenUseKeyModel> c = (o1, o2) -> {
            if(o1 .getLastUseTime() == null && o2.getLastUseTime() == null){
                return o2.getCreateTime().compareTo(o1.getCreateTime());
            }

            if(o1.getLastUseTime() != null && o2.getLastUseTime() != null){
                return o2.getLastUseTime().compareTo(o1.getLastUseTime());
            }

            return o2.getLastUseTime() != null?  1:-1;
        };

        targetList.sort(c);

        return targetList;

    }




    public static boolean writeOftenUseKeyList(List<OftenUseKeyModel> keyModelList, String uniqueId, int dbIndex){
        String keyFileName = buildFileName(uniqueId, dbIndex);

        File f = new File(keyFileName);

        ConfigUtils.writeString2File("", f);

        if(!CollectionUtils.isEmpty(keyModelList)){

            keyModelList.sort((o1, o2) -> o2.getCreateTime() > o1.getCreateTime() ? 1: -1 );

            return ConfigUtils.writeString2File( JSON.toJSONString(keyModelList), f);
        }

        return true;
    }





    private static String buildFileName(String uniqueId, int dbIndex){
        return PARENT_DIR + uniqueId + "_" + dbIndex + ".json";
    }


}
